#ifndef SIGNATURE_H_
#define SIGNATURE_H_


#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include "algo_hmac.h"


#define HMACALGO  "sha512"

std::string BinaryToHex(const char* input, unsigned int input_length)
{
    std::string strResult;
    static const char *hex = "0123456789ABCDEF";
    for (auto i = 0; i< input_length; i++)
    {
        strResult.push_back(hex[(input[i] >> 4) & 0xf]); //取二进制高四位
        strResult.push_back(hex[input[i] & 0xf]);        //取二进制低四位
    }
    return strResult;
}


std::string GenerateSignature(const std::string& appid, const std::string& appkey, 
                              const std::string& nonce, const std::string& timestamp, 
                              const std::map<std::string, std::string>& params)
{
    auto strContent = appid + nonce + timestamp;
    for (auto iter = params.begin(); iter != params.end(); ++iter)
    {
        strContent += iter->first + ":" + iter->second;
    }

    unsigned char* hmac = nullptr;
    unsigned int hmac_length = 0;
    auto ret = HmacEncode(HMACALGO, appkey.c_str(), appkey.length(),
                                strContent.c_str(), strContent.length(),
                                hmac, hmac_length);
    if (ret == 0)
    {
        std::string strResult = BinaryToHex((char*)hmac, hmac_length);
        transform(strResult.begin(), strResult.end(), strResult.begin(), ::toupper);
        return strResult;
    }
    else
    {
        return "";
    }
}

#endif /* SIGNATURE_H_ */
